package com.example.java.base.concurrency.threadpool.factory;

import java.util.concurrent.ThreadFactory;
import java.util.concurrent.atomic.AtomicInteger;

/**
 * MyThreadFactory:自定义线程工厂
 * (是把DefaultThreadFactory拿过来修改为自己需要的线程工厂参数)
 *
 * @author zhangxiaoxiang
 * @date 2021/04/16
 */
public class MyThreadFactory implements ThreadFactory {
    private static final AtomicInteger POOL_NUMBER = new AtomicInteger(1);
    private final ThreadGroup group;
    private final AtomicInteger threadNumber = new AtomicInteger(1);
    private final String namePrefix;

    /**
     * 这里构造方法可以传递参数标记一下
     */
    public MyThreadFactory() {
        SecurityManager s = System.getSecurityManager();
        group = (s != null) ? s.getThreadGroup() : Thread.currentThread().getThreadGroup();
        namePrefix = "pool-" + POOL_NUMBER.getAndIncrement() + "-thread-";
    }

    @Override
    public Thread newThread(Runnable r) {
        //group –线程组.如果为null且存在安全管理器,则该组由SecurityManager.getThreadGroup()确定.如果没有安全管理器
        // 或SecurityManager.getThreadGroup()返回null ,则该组将设置为当前线程的线程组

        //target –启动此线程时调用run方法的对象.如果为null,则调用此线程的run方法。
        // name –新线程的名称
        // stackSize –新线程所需的堆栈大小,或为零以指示该参数将被忽略。
        Thread t = new Thread(group, r, namePrefix + threadNumber.getAndIncrement(), 0);
        if (t.isDaemon()) {
            t.setDaemon(false);
        }
        if (t.getPriority() != Thread.NORM_PRIORITY) {
            t.setPriority(Thread.NORM_PRIORITY);
        }
        return t;
    }
}

